﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Web;
using Framework.Common.Cache.ICacheImplement;

namespace Framework.Common.Cache
{
    /// <summary>
    /// 缓存工厂
    /// </summary>
    public class CacheFactory
    {
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private CacheFactory()
        {
            try
            {
                string assembleDir = HttpContext.Current == null ? "/" : "~/bin";
                string assembleDirFullPath = PathHelper.MapPath(assembleDir);
                var dc = new DirectoryCatalog(assembleDirFullPath);
                var container = new CompositionContainer(dc);
                container.ComposeParts(this);
                return;
            }
            catch (ChangeRejectedException ex)
            {
                LogHelper.Debug(ex.Message, ex);
            }
            catch (Exception ex)
            {
                LogHelper.Fatal(ex.Message, ex);
            }
            Cache = new InMemoryCache();
        }

        /// <summary>
        /// MEF导入的ICache对象
        /// </summary>
        [Import]
        public ICache Cache { get; set; }

        /// <summary>
        /// 缓存工厂
        /// </summary>
        static readonly CacheFactory Factory = new CacheFactory();
        /// <summary>
        /// cache instance
        /// </summary>
        public static ICache Instance
        {
            get { return Factory.Cache; }
        }
    }
}